//
//@File    :	12.9_placenew2.cpp
//@Time    :	2021/09/14 20:20:33
//@Auther  :	Sun Sheng
//@Contact :	970340843@qq.com
//@Desc    :	new,placement new,no delete
//

#include <iostream>
#include <string>
#include <new>
using namespace std;
const int BUF = 512;
class JustTesting
{
private:
    string words;
    int number;

public:
    JustTesting(const string &s = "Just Teating", int n= 0)
    {
        words = s;
        number = n;
        cout << words << " constructed\n";
    }
    ~JustTesting() { cout << words << " destroyes\n"; }
    void Show() const { cout << words << ", " << number << endl; }
};
int main()
{
    char*buffer=new char[BUF];//buffer指向512个char型大小的内存区间

    JustTesting *pc1,*pc2;

    pc1=new(buffer) JustTesting;//place object in buffer
    pc2=new JustTesting("Heap1",20);//place object on heap
//delete不能与定位new运算符配合使用
    cout<<"Memory block addresses:\n"<<"buffer:"
        <<(void *)buffer<<"     heap: "<<pc2<<endl;
    cout<<"Memory contents:\n";
    cout<<pc1<<": ";
    pc1->Show();
    cout<<pc2<<": ";
    pc2->Show();

    JustTesting *pc3,*pc4;
//fix placement new location
    pc3=new(buffer+sizeof(JustTesting)) JustTesting("Bad Idea",6);
    pc4=new JustTesting("Heap2",10);

    cout<<"Memory contents:\n";
    cout<<pc3<<": ";
    pc3->Show();
    cout<<pc4<<": ";
    pc4->Show();
    
//注意delete正确的删除顺序,对于使用定位new运算符创建的对象,应与创建顺序相反进行删除
    delete pc2;//free Heap1
    delete pc4;//free Heap2
//explicitly destroy placement new objects
//显式地为使用定位new运算符创建的对象调用析构函数
    pc3->~JustTesting();//destroy object pointed to by pc3
    pc1->~JustTesting();//destroy object pointed to by pc1
    delete [] buffer;//free buffer释放缓存区
    cout<<"Done\n";
    system("pause");
    return 0;
}